<?php
// 后台用户模块
class Role_userAction extends CommonAction {
    function _filter(&$map){
		// admin 用户必须是id=1的。
        //$map['id'] = array('egt',1);
        //$map['user_id'] = array('egt',2);
		/*
        if(!empty($_POST['account'])) {
            $map['account'] = array('like',"%".$_POST['account']."%");
        }
		*/
    }

    // 检查帐号
    public function checkAccount() {
        if(!preg_match('/^[a-z]\w{4,}$/i',$_POST['account'])) {
            $this->error( '用户名必须是字母，且5位以上！');
        }
        $User = M("User");
        // 检测用户名是否冲突
        $name  =  $_REQUEST['account'];
        $result  =  $User->getByAccount($name);
        if($result) {
            $this->error('该用户名已经存在！');
        }else {
            $this->success('该用户名可以使用！');
        }
    }

    function edit() {
		// 修改
        $name = $this->getActionName();
        $model = M($name);
        $id = $_REQUEST [$model->getPk()];
        $vo = $model->getById($id);
		$user_id=$vo[user_id];
		// 取用户表
		$Model2=M('user');
		//$xsql="SELECT * FROM think_user ";
		unset($xlist);
		//$xlist=$Model2->query($xsql);
		$xlist=$Model2->where("id=$user_id")->select();
		if ($xlist===FALSE){
			$this->error("读取数据失败。。。");
		}
		if (count($xlist)==0) {
			$this->error("用户不存在，不能修改，请删除。。。");
		}
		$vo[account]=$xlist[0]['account'];
		$vo[nickname]=$xlist[0]['nickname'];
        $this->assign('vo', $vo);

		// 取角色表
		$Model2=M('role');
		//$xsql="SELECT * FROM think_role ";
		//$xlist=$Model2->query($xsql);
		$xlist=$Model2->select();
		if ($xlist===FALSE){
			$this->error("读取数据失败。。。");
		}
		$this->assign('vrole',$xlist);
        $this->display();
    }

    function update() {
		// 修改
		//$this->error('编辑失败aaaaaa!');
		//exit;
        $name = $this->getActionName();
        $model = D($name);
        if (false === $model->create()) {
            $this->error($model->getError());
        }
        // 更新数据
        $list = $model->save();
        if (false !== $list) {
            //成功提示
            $this->success('编辑成功!',cookie('_currentUrl_'));
        } else {
            //错误提示
            $this->error('编辑失败!');
        }
    }


    public function index() {
        //列表过滤器，生成查询Map对象
        $map = $this->_search();
        if (method_exists($this, '_filter')) {
            $this->_filter($map);
        }
        $name = $this->getActionName();
        $model = D($name);
        if (!empty($model)) {
            $this->_list($model, $map);
        }
        $this->display();
        return;
    }

    /**
      +----------------------------------------------------------
     * 根据表单生成查询条件
     * 进行列表过滤
      +----------------------------------------------------------
     * @access protected
      +----------------------------------------------------------
     * @param Model $model 数据对象
     * @param HashMap $map 过滤条件
     * @param string $sortBy 排序
     * @param boolean $asc 是否正序
      +----------------------------------------------------------
     * @return void
      +----------------------------------------------------------
     * @throws ThinkExecption
      +----------------------------------------------------------
     */
    protected function _list($model, $map, $sortBy = '', $asc = false) {
        //排序字段 默认为主键名
		if (!empty ( $_REQUEST ['_order'] )) {
			$order = $_REQUEST ['_order'];
		} else {
			$order = ! empty ( $sortBy ) ? $sortBy : $model->getPk ();
		}
		//排序方式默认按照倒序排列
		//接受 sost参数 0 表示倒序 非0都 表示正序
		if (isset ( $_REQUEST ['_sort'] )) {
//			$sort = $_REQUEST ['_sort'] ? 'asc' : 'desc';
			$sort = $_REQUEST ['_sort'] == 'asc' ? 'asc' : 'desc'; //zhanghuihua@msn.com
		} else {
			$sort = $asc ? 'asc' : 'desc';
		}
        //取得满足条件的记录数
        $count = $model->where($map)->count('id');
        if ($count > 0) {
            import("@.ORG.Util.Page");
            //import("ORG.Util.Page");
            //创建分页对象
            if (!empty($_REQUEST ['listRows'])) {
                $listRows = $_REQUEST ['listRows'];
            } else {
                $listRows = '';
            }
            $p = new Page($count, $listRows);
            //分页查询数据

            $voList = $model->where($map)->order("`" . $order . "` " . $sort)->limit($p->firstRow . ',' . $p->listRows)->select();
            //echo $model->getlastsql();
            //分页跳转的时候保证查询条件
            foreach ($map as $key => $val) {
                if (!is_array($val)) {
                    $p->parameter .= "$key=" . urlencode($val) . "&";
                }
            }
            //分页显示
            $page = $p->show();
            //列表排序显示
            $sortImg = $sort; //排序图标
            $sortAlt = $sort == 'desc' ? '升序排列' : '倒序排列'; //排序提示
            $sort = $sort == 'desc' ? 1 : 0; //排序方式

			// 取角色表
			$Model2=M('role');
			//$xsql="SELECT * FROM think_role ";
			//$xlist=$Model2->query($xsql);
			$xlist=$Model2->select();
			if ($xlist===FALSE){
				$this->error("读取数据失败。。。");
			}
			foreach ($voList as $key => $value) {
				$role_id=$value["role_id"];
				$voList[$key]['role_name']="";
				foreach ($xlist as $key2 => $value2) {
					if ($value2[id]==$role_id){
						$voList[$key]['role_name']=$value2['name'];
					}
				}
			}
			// 取用户表
			$Model2=M('user');
			//$xsql="SELECT * FROM think_user ";
			unset($xlist);
			//$xlist=$Model2->query($xsql);
			$xlist=$Model2->select();
			if ($xlist===FALSE){
				$this->error("读取数据失败。。。");
			}
			foreach ($voList as $key => $value) {
				$role_id=$value["user_id"];
				$voList[$key]['user_account']="";
				foreach ($xlist as $key2 => $value2) {
					if ($value2[id]==$role_id){
						$voList[$key]['user_account']=$value2['account']."--".$value2['nickname'];
					}
				}
			}

            //模板赋值显示
            $this->assign('list', $voList);
            $this->assign('sort', $sort);
            $this->assign('order', $order);
            $this->assign('sortImg', $sortImg);
            $this->assign('sortType', $sortAlt);
            $this->assign("page", $page);
        }
		//zhanghuihua@msn.com
		$this->assign ( 'totalCount', $count );
		$this->assign ( 'numPerPage', $p->listRows );
		$this->assign ( 'currentPage', !empty($_REQUEST[C('VAR_PAGE')])?$_REQUEST[C('VAR_PAGE')]:1);
        cookie('_currentUrl_', __SELF__);
        return;
    }

    public function add() {
		// 添加数据程序
		//echo "kkkk <br />";
		//exit;
		/*
		$x1=$this->getActionName();
		if ($x1=="Link"){
			// 取图片项目数据
			$xsql="select * from ebuy158_jpgtype order by sort ";
			//echo "$xsql <br />";
			$Model=M();
			$xlist=$Model->query($xsql);
			if ($xlist===FALSE){
				//echo "插入数据失败 $xsql2 <br />";
				$this->error("读取数据失败。。。".$xsql);
			}
			$this->assign('typelist', $xlist);
			//print_r($xlist);
			//exit;
		}
		*/
		// 取角色表
		$Model2=M('role');
		//$xsql="SELECT * FROM think_role ";
		//$xlist=$Model2->query($xsql);
		$xlist=$Model2->select();
		if ($xlist===FALSE){
			$this->error("读取数据失败。。。");
		}
		$this->assign('vrole',$xlist);
		// 取用户表
		$Model2=M('user');
		$xlist=$Model2->where("id<>1")->select();
		if ($xlist===FALSE){
			$this->error("读取数据失败。。。");
		}
		$this->assign('vuser',$xlist);
        $this->display();
    }

    // 插入数据
    public function insert() {
        // 创建数据对象
        $User	 =	 D($this->getActionName());
        if(!$User->create()) {
            $this->error($User->getError());
        }else{
            // 写入帐号数据
            if($result	 =	 $User->add()) {
                //$this->addRole($result);
                $this->success('用户添加成功！');
            }else{
                $this->error('用户添加失败！');
            }
        }
    }

    protected function addRole($userId) {
        //新增用户自动加入相应权限组
        $RoleUser = M("RoleUser");
        $RoleUser->user_id	=	$userId;
        // 默认加入网站编辑组
        $RoleUser->role_id	=	2;
        $RoleUser->add();
    }

    //重置密码
    public function resetPwd() {
        $id  =  $_POST['id'];
        $password = $_POST['password'];
        if(''== trim($password)) {
            $this->error('密码不能为空！');
        }
        $User = M('User');
        $User->password	=	md5($password);
        $User->id			=	$id;
        $result	=	$User->save();
        if(false !== $result) {
            $this->success("密码修改为$password");
        }else {
            $this->error('重置密码失败！');
        }
    }
}